package com.smart.milvus.autoconfigure;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import com.smart.milvus.bean.BaseMilvusMapper;
import com.smart.milvus.bean.MilvusClientService;
import com.smart.milvus.bean.MilvusMapperImpl;
import com.smart.milvus.bean.MilvusModel;

import java.lang.reflect.Proxy;
import java.util.Objects;

@Slf4j
@Getter
@Setter
public class MilvusClientFactoryBean<T> implements FactoryBean<T>, InitializingBean {

    private Class<? extends MilvusModel> entityClass;
    private Class<? extends BaseMilvusMapper> mapperInterface;
    private ApplicationContext applicationContext;

    @Override
    public T getObject() {
        if (Objects.isNull(entityClass)) {
            log.warn("milvus service mapper is not found");
            return null;
        }
        MilvusClientService milvusClientService = applicationContext.getBean("milvusClientService", MilvusClientService.class);
        return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(),
                new Class<?>[]{mapperInterface},
                new MilvusInvocationHandler(new MilvusMapperImpl(entityClass, milvusClientService), mapperInterface));
    }

    @Override
    public Class<?> getObjectType() {
        return mapperInterface;
    }

    @Override
    public void afterPropertiesSet() throws Exception {

    }
}
